// pages/time-slot/time-slot.js
Page({
	data: {
		selectedDoctor: '',
		selectedDate: '',
		selectedDepartment: '',
		selectedSubDepartment: '',
		selectedCampus: '湘南院区', // 添加院区信息
		// 时间段数据 - 将根据医生和日期动态生成
		timeSlots: {
			morning: [],
			afternoon: []
		}
	},

	onLoad(options) {
		console.log('时间段选择页面加载')
		// 接收从医生预约页面传递的参数
		if (options.doctor && options.date && options.department && options.subDepartment) {
			this.setData({
				selectedDoctor: options.doctor,
				selectedDate: options.date,
				selectedDepartment: options.department,
				selectedSubDepartment: options.subDepartment,
				selectedCampus: options.campus || '湘南院区' // 接收院区信息
			})
			console.log('选择的医生:', options.doctor, '日期:', options.date, '院区:', options.campus)
			
			// 根据医生和日期生成时间段数据
			this.generateTimeSlots(options.doctor, options.date, options.department)
		}
	},

	// 根据医生、日期和科室生成不同的时间段
	generateTimeSlots(doctor, date, department) {
		let morningSlots = []
		let afternoonSlots = []
		
		// 根据医生姓名生成不同的时间段模式
		const doctorHash = this.hashCode(doctor)
		const dateHash = this.hashCode(date)
		const departmentHash = this.hashCode(department)
		
		// 使用哈希值来生成不同的时间段
		const seed = (doctorHash + dateHash + departmentHash) % 100
		
		// 上午时间段（8:00-12:00）
		const morningTimes = [
			'8:00', '8:30', '9:00', '9:30', '10:00', '10:30', 
			'11:00', '11:30', '12:00'
		]
		
		// 下午时间段（13:30-17:30）
		const afternoonTimes = [
			'13:30', '14:00', '14:30', '15:00', '15:30', 
			'16:00', '16:30', '17:00', '17:30'
		]
		
		// 根据种子值选择不同的时间段组合
		const morningPatterns = [
			[0, 2, 4, 6, 8], // 8:00, 9:00, 10:00, 11:00, 12:00
			[1, 3, 5, 7],     // 8:30, 9:30, 10:30, 11:30
			[0, 1, 3, 5, 7, 8], // 8:00, 8:30, 9:30, 10:30, 11:30, 12:00
			[2, 4, 6, 8],     // 9:00, 10:00, 11:00, 12:00
			[0, 2, 4, 6],     // 8:00, 9:00, 10:00, 11:00
			[1, 3, 5, 7, 8],  // 8:30, 9:30, 10:30, 11:30, 12:00
			[0, 1, 2, 4, 6, 8], // 8:00, 8:30, 9:00, 10:00, 11:00, 12:00
			[3, 5, 7],         // 9:30, 10:30, 11:30
			[0, 2, 4, 6, 7, 8], // 8:00, 9:00, 10:00, 11:00, 11:30, 12:00
			[1, 3, 5]          // 8:30, 9:30, 10:30
		]
		
		const afternoonPatterns = [
			[0, 2, 4, 6, 8], // 13:30, 14:30, 15:30, 16:30, 17:30
			[1, 3, 5, 7],     // 14:00, 15:00, 16:00, 17:00
			[0, 1, 3, 5, 7, 8], // 13:30, 14:00, 15:00, 16:00, 17:00, 17:30
			[2, 4, 6, 8],     // 14:30, 15:30, 16:30, 17:30
			[0, 2, 4, 6],     // 13:30, 14:30, 15:30, 16:30
			[1, 3, 5, 7, 8],  // 14:00, 15:00, 16:00, 17:00, 17:30
			[0, 1, 2, 4, 6, 8], // 13:30, 14:00, 14:30, 15:30, 16:30, 17:30
			[3, 5, 7],         // 15:00, 16:00, 17:00
			[0, 2, 4, 6, 7, 8], // 13:30, 14:30, 15:30, 16:30, 17:00, 17:30
			[1, 3, 5]          // 14:00, 15:00, 16:00
		]
		
		// 选择时间段模式
		const morningPattern = morningPatterns[seed % morningPatterns.length]
		const afternoonPattern = afternoonPatterns[seed % afternoonPatterns.length]
		
		// 检查医生是否只上半天班
		const isHalfDay = this.isHalfDayDoctor(doctor, date, department)
		
		// 检查是否为特殊科室（如手术科室可能只有上午）
		const isSpecialDepartment = this.isSpecialDepartment(department)
		
		// 生成上午时间段
		morningPattern.forEach(index => {
			const remaining = this.generateRemaining(seed, index)
			morningSlots.push({
				time: morningTimes[index],
				remaining: remaining,
				available: remaining > 0,
				unavailable: remaining === -1 // 完全不可用
			})
		})
		
		// 生成下午时间段（如果医生只上半天班或特殊科室，则下午不可用）
		if (!isHalfDay && !isSpecialDepartment) {
			afternoonPattern.forEach(index => {
				const remaining = this.generateRemaining(seed, index + 10) // 加10避免与上午冲突
				afternoonSlots.push({
					time: afternoonTimes[index],
					remaining: remaining,
					available: remaining > 0,
					unavailable: remaining === -1 // 完全不可用
				})
			})
		}
		
		// 按时间排序
		morningSlots.sort((a, b) => a.time.localeCompare(b.time))
		afternoonSlots.sort((a, b) => a.time.localeCompare(b.time))
		
		this.setData({
			'timeSlots.morning': morningSlots,
			'timeSlots.afternoon': afternoonSlots
		})
	},
	
	// 生成剩余号源数量
	generateRemaining(seed, index) {
		const random = (seed * 9301 + 49297) % 233280
		const baseRemaining = (random + index * 7) % 20 // 0-19之间的随机数
		
		// 热门时间段更容易被预约满（上午9-11点，下午2-4点）
		const isHotTime = this.isHotTimeSlot(index)
		const fullProbability = isHotTime ? 4 : 2 // 热门时间段40%概率已满，普通时间段20%概率已满
		const isFull = (random + index * 11) % 10 < fullProbability
		
		// 某些时间段可能完全不可用（医生请假、设备维护等）
		const isUnavailable = (random + index * 13) % 20 < 1 // 5%的概率完全不可用
		
		if (isUnavailable) {
			return -1 // 表示完全不可用
		} else if (isFull) {
			return 0
		} else {
			return Math.floor(baseRemaining) + 1 // 1-20之间的随机数
		}
	},
	
	// 判断是否为热门时间段
	isHotTimeSlot(index) {
		// 上午热门时间段：9:00(2), 9:30(3), 10:00(4), 10:30(5), 11:00(6)
		// 下午热门时间段：14:00(1), 14:30(2), 15:00(3), 15:30(4), 16:00(5)
		const morningHotSlots = [2, 3, 4, 5, 6]
		const afternoonHotSlots = [1, 2, 3, 4, 5]
		
		return morningHotSlots.includes(index) || afternoonHotSlots.includes(index)
	},
	
	// 判断医生是否只上半天班
	isHalfDayDoctor(doctor, date, department) {
		const doctorHash = this.hashCode(doctor)
		const dateHash = this.hashCode(date)
		
		// 某些医生在某些日期只上半天班
		const halfDayProbability = (doctorHash + dateHash) % 10
		return halfDayProbability < 2 // 20%的概率只上半天班
	},
	
	// 判断是否为特殊科室
	isSpecialDepartment(department) {
		// 手术科室通常只有上午门诊
		const surgeryDepartments = ['外科', '神经外科', '心胸外科', '肝胆脾外科']
		return surgeryDepartments.includes(department)
	},
	
	// 简单的哈希函数
	hashCode(str) {
		let hash = 0
		if (str.length === 0) return hash
		for (let i = 0; i < str.length; i++) {
			const char = str.charCodeAt(i)
			hash = ((hash << 5) - hash) + char
			hash = hash & hash // 转换为32位整数
		}
		return Math.abs(hash)
	},

	selectTimeSlot(e) {
		const time = e.currentTarget.dataset.time
		const period = e.currentTarget.dataset.period
		console.log('选择了时间段:', period, time)
		
		// 跳转到确认预约页面
		wx.navigateTo({
			url: `/pages/confirm-appointment/confirm-appointment?doctor=${this.data.selectedDoctor}&date=${this.data.selectedDate}&time=${time}&department=${this.data.selectedDepartment}&subDepartment=${this.data.selectedSubDepartment}&campus=${this.data.selectedCampus}&title=主任医师&fee=60`
		})
	},

	closeModal() {
		wx.navigateBack()
	}
})
